from django.shortcuts import render
#  rest_framework
from rest_framework import generics
from rest_framework import viewsets
#  models
from django.contrib.auth import get_user_model
User = get_user_model()
from oauth2_provider.models import (
    Application, AccessToken, RefreshToken, Grant,
)
#  serializers
from api.serializers import (
    SignUpSerializer, ApplicationSerializer, UserSerializer
)
#  自定义认证类
from api.permissions import IsAuthenticatedOrCreate


# Create your views here.

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class SignUp(generics.CreateAPIView):
    queryset = User.objects.all()
    serializer_class = SignUpSerializer
    permission_classes = (IsAuthenticatedOrCreate, )

    def register(self, request, *args, **kwargs):
        ret = {'code': 1000, 'msg': None, 'data': None}

        user = request.data.get('username')
        pwd = request.data.get('password')
        obj = User.objects.filter(username=user,
                password=pwd).first()

        if not obj:
            ret['code'] = 1001
            ret['msg'] = "用户名或者密码错误"

        Application.objects.update_or_create(user=obj,
                defaults={'token': token})


class ApplicationViewSet(viewsets.ModelViewSet):
    queryset = Application.objects.all()
    serializer_class = ApplicationSerializer

